package com.xu.cloud.common.util;

import com.xu.cloud.common.constant.CodecConstant;

import java.util.Base64;

/**
 * 编码解码工具类
 *
 * @author xuguan
 * @since 2024/7/1
 */
public class CodecUtil {

    public static String hexString(byte[] bytes) {
        final char[] chars = new char[bytes.length << 1];
        for (int i = 0; i < chars.length; i = i + 2) {
            byte b = bytes[i / 2];
            chars[i] = CodecConstant.HEX_CHARS[(b >>> 0x04) & 0x0f];
            chars[i + 1] = CodecConstant.HEX_CHARS[b & 0x0f];
        }
        return new String(chars);
    }

    public static byte[] byteArray(String hex) {
        final char[] chars = hex.toCharArray();
        final byte[] bytes = new byte[chars.length >> 1];
        for (int i = 0; i < bytes.length; i++) {
            final int d1 = Character.digit(chars[i << 1], 16) << 4;
            final int d2 = Character.digit(chars[(i << 1) + 1], 16);
            bytes[i] = (byte) (d1 + d2);
        }
        return bytes;
    }

    public static String base64EncodeString(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    public static byte[] base64Decode(String encode) {
        return Base64.getDecoder().decode(encode.getBytes(CodecConstant.UTF_8));
    }

}
